package com.gzgy.ustore.api.dao.impl;

import com.gzgy.ustore.api.common.jdbc.StatementParameter;
import com.gzgy.ustore.api.dao.PdaMgrDao;
import com.gzgy.ustore.api.model.PdaMgrList;
import com.ustore.model.PdaMgr;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class PdaMgrDaoImpl extends AbstractBaseDao<PdaMgr> implements PdaMgrDao {

    @Override
    public int getPdaMgrBySn(String sn) {
        String sql ="SELECT COUNT(ID) FROM "+this.tableName+" where DVC_ID=? AND IS_DELETED = 0";
        StatementParameter parameter = new StatementParameter();
        parameter.setString(sn);
        return this.queryForInt(sql,parameter);
    }

    @Override
    public PdaMgr getPdaMgrInfoBySn(String sn) {
        String sql ="SELECT * FROM "+this.tableName+" where DVC_ID=? AND IS_DELETED = 0";
        StatementParameter parameter = new StatementParameter();
        parameter.setString(sn);
        return this.query(sql,PdaMgr.class,parameter);
    }

    @Override
    public int countPdaList(String companyId, String orgId, String dvcGroupId) {
        StatementParameter parameter = new StatementParameter();
        parameter.setString(companyId);
        parameter.setString(orgId);
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT COUNT(ID) from " + this.tableName);
        sb.append(" WHERE IS_DELETED=0 AND COMPANY_ID = ? AND INSTR(ORG_TREE_ID, ?) ");
        if (StringUtils.isNotEmpty(dvcGroupId) && !dvcGroupId.equals("0")) {
            sb.append(" AND INSTR(DVC_GROUP_ID,?) ");
            parameter.setString(dvcGroupId);
        }


        return this.queryForInt(sb.toString(), parameter);
    }

    @Override
    public List<PdaMgrList> PdaList(String companyId, String orgId, String dvcGroupId, String index, String page) {

        StatementParameter parameter = new StatementParameter();
        parameter.setString(companyId);
        parameter.setString(orgId);
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT ID,DVC_ID,DVC_TYPE,STATUS,ORG_TREE_ID,ORG_NAME,CREATED_TIME,DVC_GROUP_ID,REMARK,DVC_TOKEN from " + this.tableName);
        sb.append(" WHERE IS_DELETED=0 AND COMPANY_ID = ? AND INSTR(ORG_TREE_ID, ?) ");
        if (StringUtils.isNotEmpty(dvcGroupId) && !dvcGroupId.equals("0")) {
            sb.append(" AND INSTR(DVC_GROUP_ID,?) ");
            parameter.setString(dvcGroupId);
        }
        sb.append(" limit ?,?");
        parameter.setInt(NumberUtils.toInt(index)*NumberUtils.toInt(page));
        parameter.setInt(NumberUtils.toInt(page));
        return this.queryForList(sb.toString(), PdaMgrList.class, parameter);
    }
}
